package com.littcore.saas.wechat.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.cp.bean.WxCpDepart;
import me.chanjar.weixin.cp.bean.WxCpUser;

import com.littcore.dao.page.IPageList;
import com.littcore.dao.ql.PageParam;
import com.littcore.exception.BusiCodeException;
import com.littcore.saap.system.po.Tenant;
import com.littcore.saap.system.po.TenantMember;
import com.littcore.saap.system.po.UserInfo;
import com.littcore.saap.system.service.ITenantMemberService;
import com.littcore.saap.system.service.ITenantService;
import com.littcore.saas.wechat.service.ICpUserService;
import com.littcore.saas.wechat.service.IWechatCpService;
import com.littcore.saas.wechat.vo.WechatCpUser;
import com.littcore.util.ArrayUtils;
import com.littcore.util.BeanCopier;
import com.littcore.util.StringUtils;


/**
 * 企业号用户服务.
 * 
 * <pre><b>描述：</b>
 *    
 * </pre>
 * 
 * <pre><b>修改记录：</b>
 *    
 * </pre>
 * 
 * @author <a href="mailto:littcai@hotmail.com">蔡源</a>
 * @since 2015年9月25日
 * @version 1.0
 */
public class CpUserServiceImpl implements ICpUserService {
  
  @Resource
  private ITenantService tenantService;  
  @Resource
  private ITenantMemberService tenantMemberService;
  @Resource
  private IWechatCpService wechatCpRemote;
  
  /**
   * Sync.
   *
   * @param tenantId the tenant id
   */
  @Override
  public void doSync(int tenantId)
  {
    PageParam pageParam = new PageParam();
    pageParam.addCond("tenantId", tenantId);
    IPageList pageList = tenantMemberService.listPage(pageParam);
    List<Map<String, Object>> rsList = pageList.getRsList(); 
    
    try
    {  
      //检查是否存在租户部门，不存在则添加
      WxCpDepart cpDepart = wechatCpRemote.getDepartment(tenantId);
      if(cpDepart==null)
      {
        Tenant tenant = tenantService.load(tenantId);
        
        cpDepart = new WxCpDepart();
        cpDepart.setId(tenantId);
        cpDepart.setName(tenant.getTenantAlias());
        cpDepart.setParentId(1);
        
        wechatCpRemote.saveDepartment(cpDepart);
      }
      
      
      List<WxCpUser> curList = wechatCpRemote.getUsers(1, true, 0); //获得所有用户列表
      Map<String, WxCpUser> curCache = new HashMap<String, WxCpUser>(curList.size());
      //如果已存在，则更新租户节点
      for (int i = 0; i < curList.size(); i++)
      {
        WxCpUser curUser = curList.get(i);
        curCache.put(curUser.getEmail(), curUser);
      }
    
      List<WxCpUser> cpUsers = new ArrayList<WxCpUser>();
      for (int i = 0; i < rsList.size(); i++)
      {
        Map<String, Object> rowMap = rsList.get(i);
        TenantMember tenantMember = (TenantMember)rowMap.get("tenantMember");
        UserInfo userInfo = (UserInfo)rowMap.get("userInfo");
        
        //已存在，检查是否需要更新DepartIds
        if(curCache.containsKey(userInfo.getEmail()))
        {
          WxCpUser curCpUser = curCache.get(userInfo.getEmail());
          Integer[] departIds = curCpUser.getDepartIds();
          if(!ArrayUtils.contains(departIds, tenantId)) //已存在该用户，需要更新部门
          {
            departIds = (Integer[])ArrayUtils.add(departIds, tenantId);
            curCpUser.setDepartIds(departIds);
            curCpUser.setName(userInfo.getUserName());
            curCpUser.setGender(userInfo.getGender()+"");
            curCpUser.setMobile(StringUtils.isEmpty(userInfo.getMobile())?null:userInfo.getMobile());
            
            WechatCpUser wechatCpUser = BeanCopier.copy(curCpUser, WechatCpUser.class);
            wechatCpUser.setId(userInfo.getId());
            wechatCpUser.setLoginId(userInfo.getLoginId());
            wechatCpRemote.updateUser(wechatCpUser);
          }
          else 
          {
            if(!curCpUser.getName().equals(userInfo.getUserName()) 
                || curCpUser.getGender().equals(userInfo.getGender()+"")
                || !StringUtils.equals(curCpUser.getMobile(), userInfo.getMobile())
                || !StringUtils.equals(curCpUser.getAvatar(), userInfo.getHeadImgUrl()))             
            {
              curCpUser.setName(userInfo.getUserName());
              curCpUser.setGender(userInfo.getGender()+"");
              curCpUser.setMobile(StringUtils.isEmpty(userInfo.getMobile())?null:userInfo.getMobile());
              
              WechatCpUser wechatCpUser = BeanCopier.copy(curCpUser, WechatCpUser.class);
              wechatCpUser.setId(userInfo.getId());
              wechatCpUser.setLoginId(userInfo.getLoginId());
              wechatCpRemote.updateUser(wechatCpUser);
            }
          }
        }
        else
        {
          WechatCpUser cpUser = new WechatCpUser();
          cpUser.setId(userInfo.getId());
          cpUser.setLoginId(userInfo.getLoginId());
          cpUser.setUserId(userInfo.getId().toString());
          cpUser.setName(userInfo.getUserName());
          cpUser.setGender(userInfo.getGender()+"");
          cpUser.setMobile(StringUtils.isEmpty(userInfo.getMobile())?null:userInfo.getMobile());
          cpUser.setEmail(userInfo.getEmail());
          cpUser.setDepartIds(new Integer[]{tenantId});
          
          cpUsers.add(cpUser);
        }
      }
      wechatCpRemote.saveUsers(cpUsers.toArray(new WechatCpUser[0]));
                  
    } catch (WxErrorException e)
    {
      throw new BusiCodeException("cpUser.error.syncFailed", new Object[]{e.getError().getErrorMsg()},e);
    }
  }
  
  /**
   * 邀请租户成员关注.
   *
   * @param tenantId the tenant id
   */
  public void doInvite(int tenantId)
  {
    try
    {
      wechatCpRemote.inviteDepartmentUsers(tenantId);
    } catch (WxErrorException e)
    {
      throw new BusiCodeException("cpUser.error.inviteFailed", new Object[]{e.getError().getErrorMsg()},e);
    }
  }
  
  /**
   * 邀请租户成员关注.
   *
   * @param tenantId the tenant id
   */
  public void doInviteUser(int userId)
  {
    try
    {    
      wechatCpRemote.inviteUser(String.valueOf(userId));
    } catch (WxErrorException e)
    {
      throw new BusiCodeException("cpUser.error.inviteFailed", new Object[]{e.getError().getErrorMsg()},e);
    }
  }
  
  public void doSendMessage(int userId, String message)
  {
    try
    {    
      wechatCpRemote.sendUserMessage(4, "来自蔡源："+message, true, String.valueOf(userId));
    } catch (WxErrorException e)
    {
      throw new BusiCodeException("cpUser.error.inviteFailed", new Object[]{e.getError().getErrorMsg()},e);
    }
  }


}
